<?php
namespace common\components;
use Yii;
use yii\base\UserException;

class Controller extends \yii\web\Controller{
    //操作日志名称及描述
    public $opName = '';
    public $opDesc = '';

    public function beforeAction($action){
        Common::beginTime($action->getUniqueId());
        return parent::beforeAction($action);
    }

    public function afterAction($action, $result){
        Common::endTime($action->getUniqueId());
        $result = parent::afterAction($action, $result);
        if(!$result && strlen($result) == 0){
            Yii::$app->response->getHeaders()->set('Content-Length', 0);
        }
        return $result;
    }

    public function error($errmsg, $errcode = '1'){
        return $this->asJson([
            'errcode' => $errcode,
            'errmsg'  => $errmsg,
        ]);
    }

    public function success(array $data = []){
        if(isset($data['errcode']) || (isset($data['errmsg']))){
            throw new UserException('正文数据里不可以有errcode 或 errmsg 字段');
        }
        return $this->asJson(array_merge([
            'errcode' => 0,
            'errmsg'  => '',
        ], $data));
    }

}